package org.example.myframework.frame.demo.init;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.myframework.frame.demo.domain.entity.TestTablePlus;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 整个项目启动之后，执行初始化的方法
 */
@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {

    Map<String, InitFunction> initFunctionMap = new HashMap<>();

    {
        initFunctionMap.put("预热fastJson", this::initFastJson);
    }


    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("服务启动完成");
        // 预热HttpClient
        // 预热Json
        // initFastJson();
        initFunctionMap.forEach((desc, function) -> {
            try{
                long start = System.currentTimeMillis();
                // 依次调用方法
                function.invoke();
                log.info("当前预热的方法为：{}，执行耗时：{}", desc, System.currentTimeMillis() - start);
            } catch (Exception e) {
                // 某个方法执行失败
                throw new RuntimeException(e);
            }finally {

            }
        });
        // 预热线程池
    }

    private void initFastJson() {
        TestTablePlus testTablePlus = new TestTablePlus();
        testTablePlus.setInfo("初始化类");
        String s = JSON.toJSONString(testTablePlus);
        System.out.println(s);
        JSON.parseObject(s, TestTablePlus.class);
    }

    interface InitFunction {
        void invoke();
    }
}
